package com.gitee.swsk33.jdbcdemo.dao.impl;

import com.gitee.swsk33.jdbcdemo.config.JDBCConfig;
import com.gitee.swsk33.jdbcdemo.dao.CharacterDAO;
import com.gitee.swsk33.jdbcdemo.dataobject.Character;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CharacterDAOImpl implements CharacterDAO {

	@Override
	public int insert(Character character) {
		String sql = "insert into `character` (name, nickname, type, guild) values ('" + character.getName() + "', '" + character.getNickname() + "', '" + character.getType() + "', '" + character.getGuild() + "')";
		int count = 0;
		try {
			// 新建会话
			PreparedStatement session = JDBCConfig.getConnection().prepareStatement(sql);
			// 执行操作
			count = session.executeUpdate();
			// 关闭连接
			session.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public int delete(int id) {
		String sql = "delete from `character` where `id` = " + id;
		int count = 0;
		try {
			// 新建会话
			PreparedStatement session = JDBCConfig.getConnection().prepareStatement(sql);
			// 执行操作
			count = session.executeUpdate();
			// 关闭连接
			session.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public int update(Character character) {
		String sql = "update `character` set name = '" + character.getName() + "', nickname = '" + character.getNickname() + "', type = '" + character.getType() + "', guild = '" + character.getGuild() + "' where id = " + character.getId();
		int count = 0;
		try {
			// 新建会话
			PreparedStatement session = JDBCConfig.getConnection().prepareStatement(sql);
			// 执行操作
			count = session.executeUpdate();
			// 关闭连接
			session.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public Character getById(int id) {
		Character result = new Character();
		String sql = "select * from `character` where `id` = " + id;
		try {
			// 新建会话
			PreparedStatement session = JDBCConfig.getConnection().prepareStatement(sql);
			// 执行操作
			ResultSet resultSet = session.executeQuery();
			// 读取结果
			resultSet.next();
			result.setId(resultSet.getInt("id"));
			result.setName(resultSet.getString("name"));
			result.setNickname(resultSet.getString("nickname"));
			result.setType(resultSet.getString("type"));
			result.setGuild(resultSet.getString("guild"));
			// 关闭连接
			session.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ResultSet getAll() {
		ResultSet resultSet = null;
		try {
			PreparedStatement session = JDBCConfig.getConnection().prepareStatement("select * from `character`");
			resultSet = session.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return resultSet;
	}

}